<?php


namespace backend\controllers;


use common\helpers\commonApi;
use common\models\Goods;
use common\models\GoodsClassify;
use common\models\GoodsSpec;
use Yii;

class GoodsController extends BaseController
{
    private static $addAll = [
        ['name' => '基础设置', 'form' => 'form-basics-data'],
        ['name' => '商品规格', 'form' => 'form-price-data'],
        ['name' => '商品详情', 'form' => 'form-details-data'],
    ];
    public function init()
    {
        parent::init();
        $this->model = Goods::className();
    }

    public function actionIndex()
    {
        if (Yii::$app->request->isPost){
            $data = parent::actionIndex(true,['delete'=>0]);
            $classify_ids = array_column($data['data'],'classify_id');
            $classify = GoodsClassify::find()->where(['id'=>$classify_ids])->asArray()->all();
            $classify = array_column($classify,'name','id');
            foreach ($data['data'] as &$datum){
                $datum['classify'] = $classify[$datum['classify_id']]??'';
            }
            return $data;
        }
        return parent::actionIndex(true,['delete'=>0]);
    }
    public function actionAdd()
    {
        if (Yii::$app->request->isPost){
            $post = Yii::$app->request->post();
            $checkRes= $this->check_data($post);
            if(!$checkRes['success']){
                return $checkRes;
            }
            $model = new Goods();
            if (!$model->load($checkRes['data'], '')) {
                return commonApi::message('无提交数据', false);
            }
            if (!$model->validate()) {
                return commonApi::message(commonApi::getModelError($model), false);
            }
            $specAll = json_encode($checkRes['data']['specAll']);
            $model->sort = $checkRes['data']['sort']??0;
            $result = $model->save(false);
            if ($result) {
                $specArr = str_replace("my_good_id",$model->id,$specAll);
                $specArr = json_decode($specArr,true);
                $specModel = new GoodsSpec();
                $key = array_keys($specArr[0]);
                $specModel->insertAll($key,$specArr);
                return commonApi::message('添加成功', true);
            } else {
                return commonApi::message( '添加失败', false);
            }
        }
        $classify = GoodsClassify::find()->where(['status'=>1])->select(['id','name'])->asArray()->all();
        return $this->render('',['addAll'=>self::$addAll,'classify'=>$classify]);
    }

    /**
     * 验证数据
     * @param $data
     * @return array
     */
    public function check_data($data)
    {
        if (empty($data['name'])){
            return commonApi::message('请输入商品名称',false,['id'=>0]);
        }
        if (empty($data['main_img'])){
            return commonApi::message('请上传商品主图',false,['id'=>0]);
        }
        if (empty($data['img'])){
            return commonApi::message('请上传商品图片',false,['id'=>0]);
        }
        if (empty($data['feature'])){
            return commonApi::message('请输入商品特点',false,['id'=>0]);
        }
        if (empty($data['price'])){
            return commonApi::message('请输入商品价格',false,['id'=>0]);
        }
        if (empty($data['specAll'])){
            return commonApi::message('请选择商品规格',false,['id'=>1]);
        }
        if (!is_array($data['specAll'])){
            return commonApi::message('商品规格格式错误',false,['id'=>1]);
        }
        $specAll = [];
        foreach ($data['specAll'] as $key=>&$datum){
            $hang = $key+1;
            $hang_error = "第<span style='color: red'>$hang</span>行";
            if (empty($datum['name'])){
                return commonApi::message($hang_error."：请输入规格名称",false,['id'=>1]);
            }
            if (empty($datum['price'])){
                return commonApi::message($hang_error."：请输入价格",false,['id'=>1]);
            }
            if (!is_numeric($datum['price'])){
                return commonApi::message($hang_error."：价格必须是数字",false,['id'=>1]);
            }
            if (empty($datum['stock'])){
                return commonApi::message($hang_error."：请输入库存",false,['id'=>1]);
            }
            $datum['good_id'] = 'my_good_id';
            if (empty($datum['id'])){
                $datum['id'] = "my_good_id{$key}";
            }
            $specAll[] = [
                'g_id'=>$datum['good_id'],
                'name'=>$datum['name'],
                'price'=>$datum['price'],
                'stock'=>$datum['stock'],
                'surplus'=>$datum['stock'],
                'sales_volume'=>$datum['sales_volume'],
            ];
        }
        $data['specAll'] = $specAll;
        return  commonApi::message('',true,$data);
    }

    public function actionEdit()
    {
        if (Yii::$app->request->isPost){
            $post = Yii::$app->request->post();
            $id = $post["id"]??'';
            $model = Goods::findOne($id);
            if (!$model){
                return commonApi::message('参数错误',false);
            }
            $checkRes= $this->check_data($post);
            if(!$checkRes['success']){
                return $checkRes;
            }
            if (!$model->load($checkRes['data'], '')) {
                return commonApi::message('无提交数据', false);
            }
            if (!$model->validate()) {
                return commonApi::message(commonApi::getModelError($model), false);
            }
            $specAll = json_encode($checkRes['data']['specAll']);
            $model->sort = $checkRes['data']['sort']??0;
            $result = $model->save(false);
            if ($result) {
                $specArr = str_replace("my_good_id",$model->id,$specAll);
                $specArr = json_decode($specArr,true);
                GoodsSpec::deleteAll(['g_id'=>$model->id]);
                $specModel = new GoodsSpec();
                $key = array_keys($specArr[0]);
                $specModel->insertAll($key,$specArr);
                return commonApi::message('添加成功', true);
            } else {
                return commonApi::message( '添加失败', false);
            }
        }
        $id = Yii::$app->request->get('id','');
        $model = Goods::findOne($id);
        if (!$model){
            return $this->bError('参数错误');
        }
        $specAll = GoodsSpec::find()->where(['g_id'=>$model->id])->asArray()->all();
        $classify = GoodsClassify::find()->where(['or',['status'=>1],['id'=>$model->classify_id]])->select(['id','name'])->asArray()->all();
        return $this->render('',['info'=>$model->toArray(),'specAll'=>$specAll,'addAll'=>self::$addAll,'classify'=>$classify]);
    }

    public function actionDrop()
    {
        return parent::actionDrop();
    }
}